from datetime import date, datetime

from django.db import transaction
from django.shortcuts import render
from django.utils.timezone import make_aware

# Create your views here.

from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import status
from rest_framework import filters
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema, coreapi
from coreapi import Field
import coreschema
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django_filters.rest_framework import DjangoFilterBackend

from django.db.models import Q
from .models import DataActiontime, DataFaultcode, DataState, FanucAxis, Faultcontent
from .serializers import DataActiontimeSerializer, DataFaultcodeSerializer, DataStateSerializer, FanucAxisSerializer, FaultcontentSerializer


class DataActiontime_ViewSet(APIView):
    page_size = 10
    
    schema = AutoSchema(
        manual_fields=[
            Field(
                name='start_time',
                required=True,
                location='query',
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name='end_time',
                required=True,
                location='query',
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name='location',
                required=False,
                location='query',
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name='name',
                required=False,
                location='query',
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name='assetnum',
                required=False,
                location='query',
                schema=coreschema.String(description="设备编号"),
            )
        ]
        )

    
    def get(self, request, *args, **kwargs):
        data_actiontime_list = self.get_queryset(request)
        serializer = DataActiontimeSerializer(data_actiontime_list, many=True)
        if data_actiontime_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)
        
    def get_queryset(self, request, *args, **kwargs):
        queryset = DataActiontime.objects.all()
        
        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = DataActiontime.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
            
        # 按区域精准查询测点台账        示例：CB1 CB2 CH1 CH2
        location = request.query_params.get('location', None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")
            
        # 按测点内容模糊查询测点台账       示例：partclamp_open partclamp_close tool_close
        name = request.query_params.get('name', None)
        if name is not None:
            queryset = queryset.filter(Q(name__icontains=name))
        else:
            print("no name")
            
        # 按设备模糊查询      示例：CBM2OP20A   *当前仅有CBM2OP20A
        assetnum = request.query_params.get('assetnum', None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")


        return queryset
    
class DataFaultcode_ViewSet(APIView):
    page_size = 10
    
    schema = AutoSchema(
        manual_fields=[
            Field(
                name='start_time',
                required=True,
                location='query',
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name='end_time',
                required=True,
                location='query',
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name='assetnum',
                required=False,
                location='query',
                schema=coreschema.String(description="设备编号"),
            )
        ]
    )

    def get(self, request, *args, **kwargs):
        data_faultcode_list = self.get_queryset(request)
        serializer = DataFaultcodeSerializer(data_faultcode_list, many=True)
        if data_faultcode_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)
        
    def get_queryset(self, request, *args, **kwargs):
        queryset = DataFaultcode.objects.all()
        
        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = DataFaultcode.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
            
        # 按设备模糊查询      示例：CBM1OP20B CHM2OP120A
        assetnum = request.query_params.get('assetnum', None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")
            
        return queryset
       
class DataState_ViewSet(APIView):  
    page_size = 10
    
    schema = AutoSchema(
        manual_fields=[
            Field(
                name='start_time',
                required=True,
                location='query',
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name='end_time',
                required=True,
                location='query',
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name='name',
                required=False,
                location='query',
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name='assetnum',
                required=False,
                location='query',
                schema=coreschema.String(description="设备编号"),
            ),
            Field(
                name='location',
                required=False,
                location='query',
                schema=coreschema.String(description="设备所属区域"),
            ),
            Field(
                name='tag',
                required=False,
                location='query',
                schema=coreschema.String(description="所属动作轴"),
            )
        ]
    )
    
    def get(self, request, *args, **kwargs):
        data_state_list = self.get_queryset(request)
        serializer = DataStateSerializer(data_state_list, many=True)
        if data_state_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)
        
    def get_queryset(self, request, *args, **kwargs):
        queryset = DataState.objects.all()
        
        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = DataState.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
            
        # 按测点名称模糊搜索
        name = request.query_params.get('name', None)
        if name is not None:
            queryset = queryset.filter(Q(name__icontains=name))
        else:
            print("no name")
            
        # 按设备模糊查询      示例：CBM1OP20B CHM2OP120A
        assetnum = request.query_params.get('assetnum', None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")
            
        # 按设备所属区域模糊查询
        location = request.query_params.get('location', None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")
            
        # 按所属动作轴精确查询
        tag = request.query_params.get('tag', None)
        if tag is not None:
            queryset = queryset.filter(Q(tag__iexact=tag))
        else:
            print("no tag")
            
        return queryset
    
class FanucAxis_ViewSet(APIView):
    pagesize = 10
    
    schema = AutoSchema(

        manual_fields=[
            Field(
                name='start_time',
                required=True,
                location='query',
                schema=coreschema.String(description="开始时间"),
            ),
            Field(
                name='end_time',
                required=True,
                location='query',
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name='assetnum',
                required=False,
                location='query',
                schema=coreschema.String(description="设备编号"),
            ),
            Field(
                name='channel',
                required=False,
                location='query',
                schema=coreschema.String(description="测点类型"),
            ),
            Field(
                name='location',
                required=False,
                location='query',
                schema=coreschema.String(description="所属区域"),
                ),
        ]
    )
    
    def get(self, request, *args, **kwargs):
        fanucaxis_list = self.get_queryset(request)
        serializer = FanucAxisSerializer(fanucaxis_list, many=True)
        if fanucaxis_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)
        
    def get_queryset(self, request, *args, **kwargs):
        queryset = FanucAxis.objects.all()
        
        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = FanucAxis.objects.none()
            print("no time range")
        else:
            start_time_param_trans = make_aware(datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S"))
            end_time_param_trans = make_aware(datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S"))
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
            
        # 按设备模糊查询      示例：CBM1OP20B CHM2OP120A
        assetnum = request.query_params.get('assetnum', None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")
            
        # 按测点类型模糊查询
        channel = request.query_params.get('channel', None)
        if channel is not None:
            queryset = queryset.filter(Q(channel__icontains=channel))
        else:
            print("no channel")
            
        # 按设备所属区域模糊查询
        location = request.query_params.get('location', None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")
                
        return queryset
            
        
class Faultcontent_ViewSet(APIView):
    pagesize = 10
    
    schema = AutoSchema(

        manual_fields=[
            Field(
                name='assetnum',
                required=False,
                location='query',
                schema=coreschema.String(description="设备编号"),
            ),
            Field(
                name='location',
                required=False,
                location='query',
                schema=coreschema.String(description="设备所属区域"),
            ),
            Field(
                name='level',
                required=False,
                location='query',
                schema=coreschema.Integer(description="报警等级"),
            ),
            Field(
                name='code',
                required=False,
                location='query',
                schema=coreschema.String(description="报警代码"),
            ),
            Field(
                name='name',
                required=False,
                location='query',
                schema=coreschema.String(description="报警点位"),
            ),
            Field(
                name='description',
                required=False,
                location='query',
                schema=coreschema.String(description="报警描述"),
            ),
            Field(
                name='remark',
                required=False,
                location='query',
                schema=coreschema.String(description="备注"),
            ),
        ]
    )
    
    def get(self, request, *args, **kwargs):
        faultcontent_list = self.get_queryset(request)
        serializer = FaultcontentSerializer(faultcontent_list, many=True)
        if faultcontent_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_400_BAD_REQUEST)
        
    def get_queryset(self, request, *args, **kwargs):
        queryset = Faultcontent.objects.all()
        
        # 按设备编号模糊查询
        assetnum = request.query_params.get('assetnum', None)
        if assetnum is not None:
            queryset = queryset.filter(Q(assetnum__icontains=assetnum))
        else:
            print("no assetnum")
            
        # 按设备所属区域模糊查询
        location = request.query_params.get('location', None)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")
            
        # 按报警等级精确查询
        level = request.query_params.get('level', None)
        if level is not None:
            queryset = queryset.filter(Q(level__exact=level))
        else:
            print("no level")
            
        # 按报警代码模糊查询
        code = request.query_params.get('code', None)
        if code is not None:
            queryset = queryset.filter(Q(code__icontains=code))
        else:
            print("no code")
            
        # 按报警点位模糊查询
        name = request.query_params.get('name', None)
        if name is not None:
            queryset = queryset.filter(Q(name__icontains=name))
        else:
            print("no name")
            
        # 按报警描述模糊查询
        description = request.query_params.get('description', None)
        if description is not None:
            queryset = queryset.filter(Q(description__icontains=description))
        else:
            print("no description")
            
        # 按备注模糊查询
        remark = request.query_params.get('remark', None)
        if remark is not None:
            queryset = queryset.filter(Q(remark__icontains=remark))
        else:
            print("no remark")
        
        return queryset











            





           
